package cn.steel.service.impl;


import cn.steel.domain.dto.SupplierRatingDto;
import cn.steel.domain.entity.Order;
import cn.steel.domain.entity.SupplierInfo;
import cn.steel.domain.entity.SupplierRating;
import cn.steel.domain.vo.SupplierRatingVo;
import cn.steel.mapper.OrderMapper;
import cn.steel.mapper.SupplierInfoMapper;
import cn.steel.mapper.SupplierRatingMapper;
import cn.steel.service.SupplierRatingService;
import cn.steel.utils.BusinessException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class SupplierRatingServiceImpl implements SupplierRatingService {

    private final SupplierRatingMapper ratingMapper;
    private final SupplierInfoMapper supplierInfoMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    private static final String RATING_CACHE_KEY = "supplier:rating:";

    private final  OrderMapper orderMapper;


    @Override
    @Transactional
    public void submitRating(Long userId, SupplierRating rating) {
        rating.setUserId(userId);
        rating.setCreateTime(LocalDateTime.now());
        ratingMapper.insertRating(rating);

        // 更新平均评分
        Double averageRating = ratingMapper.calculateAverageRating(rating.getSupplierId());
        SupplierInfo supplierInfo = supplierInfoMapper.findByUserId(rating.getSupplierId());
        if (supplierInfo != null) {
            supplierInfo.setAverageRating(averageRating != null ? averageRating : 0.0);
            supplierInfo.calculateStars(); // 确保每次更新评分后都重新计算星级
            supplierInfoMapper.updateSupplierInfo(supplierInfo);
            log.info("Updated SupplierInfo: supplierId={}, averageRating={}, fullStars={}, hasHalfStar={}",
                    rating.getSupplierId(), supplierInfo.getAverageRating(), supplierInfo.getFullStars(), supplierInfo.getHasHalfStar());
        }

        // 清除缓存
        redisTemplate.delete(RATING_CACHE_KEY + rating.getSupplierId());
        log.info("供应商评价提交成功: supplierId={}", rating.getSupplierId());
    }

    @Override
    public Page<SupplierRating> getRatingsPaginated(Long supplierId, int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<SupplierRating>) ratingMapper.findBySupplierId(supplierId);
    }

    @Override
    public Double getAverageRating(Long supplierId) {
        String cacheKey = RATING_CACHE_KEY + supplierId;
        Double cachedRating = (Double) redisTemplate.opsForValue().get(cacheKey);
        if (cachedRating != null) {
            return cachedRating;
        }

        Double averageRating = ratingMapper.calculateAverageRating(supplierId);
        averageRating = averageRating != null ? averageRating : 0.0; // 确保返回 0.0 而不是 null
        redisTemplate.opsForValue().set(cacheKey, averageRating, 1, TimeUnit.HOURS);
        return averageRating;
    }
    @Override
    public List<SupplierRatingVo> getRatingsBySupplier(Long supplierId) {
        return ratingMapper.selectBySupplierId(supplierId);
    }

    @Override
    public List<SupplierRatingVo> getRatingsByUser(Long userId) {
        return ratingMapper.selectByUserId(userId);
    }

    @Override
    public SupplierRatingVo getRatingDetail(Long orderId) {
        return ratingMapper.selectRatingDetail(orderId);
    }


    @Override
    @Transactional
    public void submitBuyerRating(Long userId, Long supplierId, SupplierRatingDto ratingDto) {
        // 通过orderNo查询订单
        Order order = orderMapper.getOrderByOrderNo(ratingDto.getOrderNo());

        // 验证订单是否存在
        if (order == null) {
            throw new BusinessException("订单不存在或已被删除");
        }

        log.info("订单ID: {}, 订单状态: {}", ratingDto.getOrderId(), order.getStatus());

        // 检查是否已经评价过
        SupplierRating existingRating = ratingMapper.selectByOrderIdAndUserId(ratingDto.getOrderId(), userId);
        if (existingRating != null) {
            throw new BusinessException("您已经评价过该订单");
        }

        // 创建评价
        SupplierRating rating = new SupplierRating();
        rating.setUserId(userId);
        rating.setSupplierId(supplierId);
        rating.setOrderId(ratingDto.getOrderId());
        rating.setOrderNo(ratingDto.getOrderNo()); // 确保保存订单编号
        rating.setRating(ratingDto.getRating());
        rating.setComment(ratingDto.getComment());

        ratingMapper.insert(rating);
    }
    @Override
    public boolean canRateOrder(Long orderId, Long userId) {
        Order order = orderMapper.selectById(orderId);
        if (order == null) return false;

        // 修改为只检查是否已经评价过和订单是否属于当前用户
        return !ratingMapper.existsByOrderId(orderId)
                && order.getBuyerId().equals(userId);
    }
    @Override
    public void submitRating(SupplierRatingDto supplierRatingDto) throws Exception {
        // 验证输入
        if (supplierRatingDto.getOrderId() == null || supplierRatingDto.getSupplierId() == null) {
            throw new Exception("订单ID或供应商ID不能为空");
        }
        if (supplierRatingDto.getRating() < 1 || supplierRatingDto.getRating() > 5) {
            throw new Exception("评分必须在1到5之间");
        }

        // 检查是否已评价
        SupplierRating existingRating = ratingMapper.findByOrderIdAndSupplierId(
                supplierRatingDto.getOrderId(), supplierRatingDto.getSupplierId());
        if (existingRating != null) {
            throw new Exception("该订单已评价过此供应商");
        }

        // 转换为实体
        SupplierRating rating = new SupplierRating();
        rating.setOrderId(supplierRatingDto.getOrderId());
        rating.setSupplierId(supplierRatingDto.getSupplierId());
        rating.setOrderNo(supplierRatingDto.getOrderNo());
        rating.setRating(supplierRatingDto.getRating());
        rating.setComment(supplierRatingDto.getComment());
        rating.setCreateTime(java.time.LocalDateTime.now());
        // 设置 userId
        rating.setUserId(supplierRatingDto.getUserId());

        // 保存评价
        ratingMapper.insert(rating);
    }
}

